const express = require('express');
const router = express.Router();
const Utils = require("../util/Utils");
const RedisUtil = require("../util/RedisUtil");
const CacheKeyUtil = require("../util/CacheKeyUtil");

router.get('/:owner/:repo', async function (req, res, next) {
    await doRequest(req, res);
});

async function doRequest(req, res) {
    // 仓库所有者
    const owner = req.params.owner
    // 仓库名
    const repo = req.params.repo

    if(!owner || !repo) {
        console.log("owner 或者 repo 不全")
        res.render('index', {
            owner: owner,
            repo: repo,
            startTime: "",
            expireTime: null,
            starTotal: 0,
            error: '请指定 owner 和 repo'
        });
        return;
    }
    // 数据过期时间，不填时默认取 {@code config.redis.expire}
    let expire = Utils.getRealExpireTime(req.query.e)
    const page = 1

    const repoKey = CacheKeyUtil.repoKey(owner, repo);
    const maxPageKey = CacheKeyUtil.maxPageKey(repoKey);
    const totalKey = CacheKeyUtil.totalKey(repoKey);
    const pageKey = CacheKeyUtil.pageKey(repoKey, page);
    const starTotal = await RedisUtil.get(totalKey)
    if (starTotal) {
        console.log("进入", repoKey, "页面，有缓存，直接返回")
        res.render('index', {
            owner: owner,
            repo: repo,
            startTime: "",
            expireTime: expire,
            starTotal: starTotal,
        });
        return;
    }
    Utils.request(await Utils.parseStargazersUrl(owner, repo, page), function (response, starArray) {
        const map = Utils.groupBy(starArray, function (item) {
            return item.star_at.substr(0, 10)
        }, {})
        RedisUtil.set(pageKey, map, expire);

        const headers = response.headers;
        const starTotal = parseInt(headers.total_count)
        const starPage = parseInt(headers.total_page)
        RedisUtil.set(maxPageKey, starPage, expire);
        RedisUtil.set(totalKey, starTotal, expire);

        res.render('index', {
            owner: owner,
            repo: repo,
            startTime: "",
            expireTime: expire,
            starTotal: starTotal,
        });
    }, function (err) {
        console.log(err)
        res.render('index', {
            owner: owner,
            repo: repo,
            startTime: "",
            expireTime: expire,
            starTotal: -1,
            error: err
        });
    })
}

module.exports = router;
